package test.com.trgis.qtmap.commons.database.mongo;

import java.net.UnknownHostException;
import java.util.regex.Pattern;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;

public class TRMongoDB {

	private String dbName;

	private Mongo mongo;

	public TRMongoDB(String dbName) {
		this.dbName = dbName;
	}

	/**
	 * 初始化数据库连接
	 * 
	 * @throws UnknownHostException
	 */
	protected Mongo getMongo() throws UnknownHostException {
		if (mongo == null) {
			mongo = new MongoClient();
		}
		return mongo;
	}

	public DB getDB() throws UnknownHostException {
		return getDB(dbName);
	}
	
	public DB getDB(String dbName) throws UnknownHostException {
		this.dbName = dbName;
		return getMongo().getDB(dbName);
	}

	/**
	 * 创建表
	 */
	public void createCollection(String collectionName) {
		try {
			getDB().createCollection(collectionName, new BasicDBObject());
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取数据库链接
	 * @param collectionName
	 * @return
	 * @throws UnknownHostException
	 */
	public DBCollection getDBCollection(String collectionName)
			throws UnknownHostException {
		return getDB(dbName).getCollection(collectionName);
	}
	
	/**
	 * 获取指定数据库的连接
	 * @param dbName
	 * @param collectionName
	 * @return
	 * @throws UnknownHostException
	 */
	public DBCollection getDBCollection(String dbName, String collectionName)
			throws UnknownHostException {
		return getDB(dbName).getCollection(collectionName);
	}

	/**
	 * 获取指定collection表对应的数据
	 */
	public DBCursor getDBCursor(String collectionName,String key,String val) throws UnknownHostException{
		BasicDBObject query = new BasicDBObject();
		query.put(key, Pattern.compile(val));
		DBCursor cursor = getDBCollection(collectionName).find(query);
		return cursor;
	}
	
	public DBCursor getDBCursor(String collectionName) throws UnknownHostException{
		DBObject keys = new BasicDBObject();
		keys.put("name", 1);
		return getDBCollection(collectionName).find(new BasicDBObject(), keys);
	}
	
	public WriteResult insertDBObject(String collectionName,DBObject obj) throws UnknownHostException{
		WriteResult result = getDBCollection(collectionName).insert(obj);
		return result;
	}
}
